<template>
  <div class="friends-panel-container">
    <div class="list-container">
      <div class="tab-group">
        <v-tabs
            fixed-tabs icons centered
            background-color="transparent"
            height="30"
            :color="customerColor"
            @change="handleTabsChange">
          <v-tab>
            <v-icon small>fas fa-user</v-icon>
          </v-tab>
          <v-tab>
            <v-icon small>fas fa-users</v-icon>
          </v-tab>
          <v-tab>
            <v-icon small>fas fa-user-tag</v-icon>
          </v-tab>
        </v-tabs>
        <v-window
            v-model="currentList">
          <v-window-item :value="0" class="friend-list-container">
            <div class="tab-title">
              <div class="title-text">
                我的好友
              </div>
              <div
                  class="add-btn"
                  v-ripple
                  @click="handleAddFriendClick">
                <v-icon size="13" color="#888">fas fa-plus</v-icon>
                添加好友
              </div>
            </div>
            <div
                class="friend-item-container"
                v-for="friend in friendList"
                :id="friend.id"
                @click="handleFriendClick(friend.roomId)"
                v-ripple>
              <v-avatar size="30">
                <img
                    :src="friend.avatar"
                    alt="John">
              </v-avatar>
              <div class="friend-name">
                {{ getFriendName(friend) }}
              </div>
              <div class="text-center" style="margin: auto auto">
                <v-menu
                    open-on-hover
                    offset-y
                    transition="scale-transition"
                    light
                >
                  <template v-slot:activator="{ on, attrs }">
                    <span class="el-dropdown-link" v-bind="attrs" v-on="on">
                      <v-icon
                          color="green"
                          disabled>
                          mdi-format-list-bulleted
                      </v-icon>
                </span>
                  </template>

                  <v-list>
                    <v-list-item @click="handleFriendClick(friend.roomId)">
                      <v-list-item-title>私聊</v-list-item-title>
                    </v-list-item>
                    <v-list-item @click="handleShowSetUpBeiZuValuePopup(friend)">
                      <v-list-item-title>设置备注</v-list-item-title>
                    </v-list-item>
                    <v-list-item @click="handleShowSetUpFenZuPopup(friend)">
                      <v-list-item-title>设置分组</v-list-item-title>
                    </v-list-item>
                    <v-list-item
                    >
                      <v-list-item-title>拉黑</v-list-item-title>
                    </v-list-item>
                  </v-list>
                </v-menu>
              </div>
            </div>
          </v-window-item>
          <v-window-item :value="1" class="group-list-container">
            <div class="tab-title">
              <div class="title-text" @click="handleShowCreateGroupChatPopup()">
                创建群聊
              </div>
              <div
                  class="add-btn"
                  v-ripple
                  @click="handleAddFriendClick">
                <v-icon size="13" color="#888">fas fa-plus</v-icon>
                加入新群聊
              </div>
            </div>

            <div v-if="groupCreateList.length!==0">
              <v-divider></v-divider>
              <div class="group-title-text" >
                我创建的
              </div>
              <div
                  class="friend-item-container"
                  v-for="group in groupCreateList"
                  :id="group.id"
                  v-ripple>
                <v-avatar size="30">
                  <img
                      :src="group.img"
                      alt="John">
                </v-avatar>
                <div class="friend-name">
                  {{ group.title }} ({{ group.userNum }})
                </div>
              </div>
            </div>
            <div v-if="groupList.length!==0">
              <v-divider></v-divider>
              <div class="group-title-text">
                我加入的
              </div>
              <div
                  class="friend-item-container"
                  v-for="group in groupList"
                  :id="group.groupInfo[0].id"
                  v-ripple>
                <v-avatar size="30">
                  <img
                      :src="group.groupInfo[0].img"
                      alt="John">
                </v-avatar>
                <div class="friend-name">
                  {{ group.groupInfo[0].title }} ({{ group.groupInfo[0].userNum }})
                </div>
              </div>
            </div>
            <div v-if="groupCreateList.length===0&&groupList.length===0">
              <el-empty  description="未获取到群聊数据"></el-empty>
            </div>

          </v-window-item>
          <v-window-item :value="2" class="group-list-container">
            <div class="tab-title">
              <div class="title-text">
                我的分组
              </div>
              <div
                  class="add-btn"
                  v-ripple
                  @click="handleShowManageFenZuPopup">
                <v-icon size="13" color="#888">fas fa-plus</v-icon>
                管理分组
              </div>
            </div>
            <el-collapse v-model="activeUserGroup" @change="handleChange">
              <el-collapse-item v-for="(item,index) in friendFenZu" :title="index">
                <div
                    class="friend-item-container"
                    v-for="friendId in item"
                    :id="userList[friendId].id"
                    @click="handleFriendClick(userList[friendId].roomId)"
                    v-ripple>
                  <v-avatar size="30">
                    <img
                        :src="userList[friendId].avatar"
                        alt="John">
                  </v-avatar>
                  <div class="friend-name">
                    {{ getFriendName(userList[friendId]) }}
                  </div>
                </div>
              </el-collapse-item>
            </el-collapse>
          </v-window-item>
        </v-window>
      </div>
    </div>
    <div class="user-profile-container">
      <userProfile/>
    </div>
    <v-dialog
        v-model="showSearchUserPopup"
        class="rounded-xl"
        width="50vw"
        max-width="700"
        @close="showSearchUserPopup = false">
      <div class="search-user-popup-container">
        <div class="title-text">
          搜索朋友
        </div>
        <v-text-field
            label="请输入昵称/关键词/用户ID"
            clearable
            v-model="searchValue"
            :color="customerColor"
            type="text"
            append-outer-icon="fas fa-search"
            @click:append-outer="handleSearchFriendClick"></v-text-field>
        <searchUser
            v-model="searchValue"
            v-if="searchUserTrigger"/>
      </div>
    </v-dialog>
    <v-dialog
        v-model="showManageFenZuPopup"
        class="rounded-xl"
        width="50vw"
        max-width="700"
        transition="scale-transition"
        @close="showManageFenZuPopup = false">
      <div class="search-user-popup-container">
        <div class="title-text">
          分组管理
        </div>

        <v-list flat>
          <v-subheader style="cursor:pointer" @click="handleShowAddFenZuPopup()">添加分组</v-subheader>
          <v-list-item-group
              v-model="selectedItem"
              color="primary"
          >
            <div v-for="(item, i) in friendFenZu"
                 :key="i">
              <v-list-item
              >
                <v-list-item-content @click="handleShowUpdateFenZuClick(i)">
                  <v-list-item-title v-text="i"></v-list-item-title>
                </v-list-item-content>
                <v-list-item-icon @click="handleDeleteFenZu(i)">
                  <v-icon>mdi-trash-can-outline</v-icon>
                </v-list-item-icon>
              </v-list-item>
            </div>
          </v-list-item-group>
        </v-list>

      </div>
    </v-dialog>

    <v-dialog
        v-model="showUpdateFenZuPopup"
        class="rounded-xl"
        width="50vw"
        max-width="700"
        @close="handleCloseUpdateFenZuClick()">
      <div class="search-user-popup-container">
        <div class="title-text">
          修改分组
        </div>
        <v-text-field
            label="请输入新的分组"
            clearable
            v-model="updateFenZuValue"
            :color="customerColor"
            type="text"
        ></v-text-field>
        <div class="my-2 center" style="margin: 0 auto">
          <v-btn
              color="primary"
              dark
              @click="handleUpdateFenZu()"
          >
            提 交
          </v-btn>
        </div>
      </div>
    </v-dialog>

    <v-dialog
        v-model="showAddFenZuPopup"
        class="rounded-xl"
        width="50vw"
        max-width="700"
        @close="handleCloseAddFenZuPopup()">
      <div class="search-user-popup-container">
        <div class="title-text">
          添加分组
        </div>
        <v-text-field
            label="请输入新的分组"
            clearable
            v-model="addFenZuValue"
            :color="customerColor"
            type="text"
        ></v-text-field>
        <div class="my-2 center" style="margin: 0 auto">
          <v-btn
              color="primary"
              dark
              @click="handleAddFen()"
          >
            提 交
          </v-btn>
        </div>
      </div>
    </v-dialog>

    <v-dialog
        v-model="showSetUpBeiZuValuePopup"
        class="rounded-xl"
        width="50vw"
        max-width="700"

        @close="handleCloseSetUpBeiZuValuePopup()">
      <div class="search-user-popup-container">
        <div class="title-text">
          设置备注
        </div>
        <v-text-field
            label="请输入备注"
            clearable
            v-model="setUpBeiZuValue"
            :color="customerColor"
            type="text"
        ></v-text-field>
        <div class="my-2 center" style="margin: 0 auto">
          <v-btn
              color="primary"
              dark
              @click="handleSetUpBeiZu()"
          >
            提 交
          </v-btn>
        </div>
      </div>
    </v-dialog>

    <v-dialog
        v-model="showSetUpFenZuPopup"
        class="rounded-xl"
        width="50vw"
        max-width="700"

        @close="handleCloseSetUpFenZuPopup()">
      <div class="search-user-popup-container">
        <div class="title-text">
          设置分组
        </div>
        <v-select
            :items="fenZuNames"
            label="请选择对应分组"
            dense
            v-model="setUpFenZuValue"
        ></v-select>
        <div class="my-2 center" style="margin: 0 auto">
          <v-btn
              color="primary"
              dark
              @click="handleSetUpFenZu()"
          >
            提 交
          </v-btn>
        </div>
      </div>
    </v-dialog>


    <v-dialog
        v-model="showCreateGroupChatPopup"
        class="rounded-xl"
        width="50vw"
        max-width="700"
        @close="handleCloseCreateGroupChatPopup()">
      <div class="search-user-popup-container">
        <div class="title-text">
          创建群聊
        </div>
        <v-text-field
            label="请输群聊名称"
            clearable
            v-model="createGroupChat.title"
            :color="customerColor"
            type="text"
        ></v-text-field>
        <v-text-field
            label="请输群聊描述"
            clearable
            v-model="createGroupChat.desc"
            :color="customerColor"
            type="text"
        ></v-text-field>
        <div class="desc-text">
          群聊头像 :
        </div>
        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        <el-upload
            class="avatar-uploader"
            action="api/oss/file/upload?model=chat"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
          <img v-if="createGroupChat.imageUrl" :src="createGroupChat.imageUrl" class="avatar" alt="头像">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <div class="my-2 center" style="margin: 0 auto">
          <v-btn
              color="primary"
              dark
              @click="handleCreateGroupChat()"
          >
            提 交
          </v-btn>
        </div>
      </div>
    </v-dialog>
  </div>
</template>

<script>
import userProfile from "@/components/chat/userProfile/userProfile";
import searchUser from "@/components/chat/searchUser/searchUser";
import {
  addFenZu,
  createGroup,
  deleteFenZu,
  getMyFriendList,
  getMyGroupList,
  getUserInfo,
  modifyFriendBeiZhu,
  modifyFriendFenZu,
  updateFenZuName,
  getMyCreateGroupList
} from "../../../api";

export default {
  name: "friendsPanel",
  components: {
    userProfile, searchUser
  },
  data() {
    return {
      customerColor: '',
      friendList: [],
      currentList: 0,
      showSearchUserPopup: false,
      searchValue: '',
      searchUserTrigger: false,
      groupList: [],
      userInfo: {},
      activeUserGroup: "1",
      friendFenZu: {},
      userList: {},
      showUpdateFenZuPopup: false,
      updateFenZuValue: "",
      oldFenZuValue: "",
      showManageFenZuPopup: false,
      selectedItem: 1,
      showAddFenZuPopup: false,
      addFenZuValue: "",
      showSetUpBeiZuValuePopup: false,
      setUpBeiZuValue: "",
      setUpBeiZuFriend: {},
      showSetUpFenZuPopup: false,
      setUpFenZuValue: "",
      fenZuNames: [],
      setUpFenZuFriend: {},
      showCreateGroupChatPopup: false,
      createGroupChat: {
        title: "",
        desc: "",
        imageUrl: ''
      },
      groupCreateList: []
    }
  },
  methods: {
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    handleAvatarSuccess(res, file) {
      if (res.success) {
        this.createGroupChat.imageUrl = res.data.filePath
      } else {
        this.$message.error('头像上传失败');
      }
    },
    handleChange(val) {
      console.log(val);
    },
    getFriendName(friend) {
      let friendBeiZhu = this.userInfo.friendBeiZhu;
      let keys = Object.keys(friendBeiZhu);
      if (keys.length !== 0) {
        let id = friend.id;
        let friendBeiZhuElement = friendBeiZhu[id];
        if (friendBeiZhuElement != null) {
          return friendBeiZhuElement;
        }
      }
      return friend.nickname

    },
    handleTabsChange(index) {
      this.currentList = index;
    },
    handleShowCreateGroupChatPopup() {
      this.showCreateGroupChatPopup = true
    },
    handleCloseCreateGroupChatPopup() {
      this.showCreateGroupChatPopup = false
      this.createGroupChat = {}
    },
    // 设置好友分组弹窗
    handleShowSetUpFenZuPopup(friend) {
      this.showSetUpFenZuPopup = true
      this.setUpFenZuFriend = friend

    },

    handleCloseSetUpFenZuPopup() {
      this.showSetUpFenZuPopup = false
      this.setUpFenZuFriend = {}
      this.setUpFenZuValue = ""
    },
    // 设置备注
    handleShowSetUpBeiZuValuePopup(friend) {
      let friendBeiZhu = this.userInfo.friendBeiZhu;
      let id = friend.id;
      let keys = Object.keys(friendBeiZhu);
      if (keys.length !== 0) {
        this.setUpBeiZuValue = friendBeiZhu[id];
      }
      this.setUpBeiZuFriend = friend
      this.showSetUpBeiZuValuePopup = true
    },
    handleCloseSetUpBeiZuValuePopup() {
      this.showSetUpBeiZuValuePopup = false
      this.setUpBeiZuValue = ""
    },
    // 添加朋友
    handleAddFriendClick() {
      this.showSearchUserPopup = true;
    },
    // 添加分组
    handleShowAddFenZuPopup() {
      this.showAddFenZuPopup = true
      this.showManageFenZuPopup = false
    },
    handleCloseAddFenZuPopup() {
      this.showAddFenZuPopup = false
      this.showManageFenZuPopup = true
      this.addFenZuValue = ""
    },
    // 显示修改分组名称对话框
    handleShowUpdateFenZuClick(fenZuName) {
      this.showUpdateFenZuPopup = true;
      this.showManageFenZuPopup = false
      this.updateFenZuValue = fenZuName
      this.oldFenZuValue = fenZuName
    },
    handleCloseUpdateFenZuClick() {
      this.showUpdateFenZuPopup = false;
      this.showManageFenZuPopup = true
      this.updateFenZuValue = ""
    },
    handleShowManageFenZuPopup() {
      this.showManageFenZuPopup = true
    },
    handleSearchFriendClick() {
      this.searchUserTrigger = false;
      this.$nextTick(() => {
        this.searchUserTrigger = true;
      });
    },
    handleFriendClick(id) {
      this.$emit('goToFriendChat', id);
    },
    // 设置分组
    async handleSetUpFenZu() {
      console.log(this.setUpFenZuValue)
      let res = await modifyFriendFenZu(this.userInfo.id, this.setUpFenZuFriend.id, this.setUpFenZuValue)
      if (res.success) {
        await this.refreshUserInfo()
        this.$message.success('设置分组成功');
      } else {
        this.$message.error('设置分组失败');
      }
      this.handleCloseSetUpFenZuPopup()
    },

    // 创建群聊
    async handleCreateGroupChat() {
      let res = await createGroup(this.createGroupChat.title, this.createGroupChat.desc, this.createGroupChat.imageUrl, this.userInfo.id, this.userInfo.nickname)
      if (res.success) {
        this.$message.success('创建群聊成功');
        await this.getMyGroupList();
      } else {
        this.$message.error('创建群聊失败');
      }
    },
    // 设置备注
    async handleSetUpBeiZu() {
      let res = await modifyFriendBeiZhu(this.setUpBeiZuFriend.id, this.setUpBeiZuValue);
      if (res.success) {
        await this.refreshUserInfo()
        this.$message.success('设置备注成功');
      } else {
        this.$message.error('设置备注失败');
      }
      this.handleCloseSetUpBeiZuValuePopup()
    },
    async handleDeleteFenZu(fenZuName) {
      this.$confirm('此操作将删除改分组, 是否继续?', '删除分组', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res = await deleteFenZu(this.userInfo.id, fenZuName)
        if (res.success) {
          await this.refreshUserInfo()
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        } else {
          this.$message.error('修改失败失败');
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

    },
    async handleUpdateFenZu() {
      let res = await updateFenZuName(this.userInfo.id, this.oldFenZuValue, this.updateFenZuValue)
      if (res.success) {
        this.$message.success('修改成功');
        // 刷新分组列表
        await this.refreshUserInfo()
      } else {
        this.$message.error('修改失败失败');
      }
      this.handleCloseUpdateFenZuClick()
    },
    // 添加分组
    async handleAddFen() {
      let res = await addFenZu(this.userInfo.id, this.addFenZuValue)
      if (res.success) {
        this.$message.success('添加成功');
        // 刷新分组列表
        await this.refreshUserInfo()
      } else {
        this.$message.error('添加失败失败');
      }
      this.handleCloseAddFenZuPopup()
    },

    async refreshUserInfo() {
      let res = await getUserInfo(this.userInfo.id);
      let userInfo = res.data;
      sessionStorage.setItem("userInfo", JSON.stringify(userInfo));
      this.userInfo = userInfo
      this.friendFenZu = userInfo.friendFenZu
      let fenZuNames = []
      for (const fenZu in this.friendFenZu) {
        fenZuNames.push(fenZu)
      }
      this.fenZuNames = fenZuNames;

    },
    updateColor() {
      this.customerColor = document.getElementsByTagName('body')[0].style.getPropertyValue('--custom-color');
    },
    async getMyFriendList() {
      let res = await getMyFriendList()
      if (res.success) {
        this.friendList = res.data
      } else {
        this.$message.error('获取好友列表失败！');
      }
    },
    async getMyCreateGroupList() {
      const groupListRes = await getMyCreateGroupList();
      this.groupCreateList = groupListRes.data;
    },
    async getMyGroupList() {
      const groupListRes = await getMyGroupList();
      this.groupList = groupListRes.data;
    },
    async init() {
      this.userInfo = JSON.parse(sessionStorage.getItem("userInfo"));
      this.friendFenZu = this.userInfo.friendFenZu;
      let userIds = [];
      // 收集用户id
      for (const fenZu in this.friendFenZu) {
        for (const userIdIndex in this.friendFenZu[fenZu]) {
          userIds.push(this.friendFenZu[fenZu][userIdIndex]);
        }
      }
      userIds = Array.from(new Set(userIds))
      for (const userId of userIds) {
        let res = await getUserInfo(userId);
        this.userList[userId] = res.data
      }
      let fenZuNames = []
      for (const fenZu in this.friendFenZu) {
        fenZuNames.push(fenZu)
      }
      this.fenZuNames = fenZuNames;
    },
  },
  watch: {
    showSearchUserPopup(nval) {
      if (!nval) {
        this.searchUserTrigger = false;
        this.searchValue = '';
      }
    },
    searchValue(nval) {
      if (nval === '') {
        this.searchUserTrigger = false;
      }
    }
  },
  async mounted() {
    await this.init()
    await this.getMyFriendList();
    await this.getMyGroupList()
    await this.getMyCreateGroupList()
    this.customerColor = document.getElementsByTagName('body')[0].style.getPropertyValue('--custom-color') ?? '#4746a3';
  },
  async created() {

  }
}
</script>

<style lang="scss" scoped>
@import 'friendsPanel.scss';
</style>